import { Injectable } from '@nestjs/common';
import { CreateUserDto,findUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Repository, Like } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Article } from '../article/entities/article.entity';
import { Comment } from '../comment/entities/comment.entity';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly user: Repository<User>,
    @InjectRepository(Article) private readonly article: Repository<Article>,
    @InjectRepository(Comment) private readonly comment: Repository<Comment>
  ) { }
  create(createUserDto: CreateUserDto) {
    const data = new User()
    data.username = createUserDto.username
    return this.user.save(data)
  }

  async findAll(query: { keyWord: string, page: number, pageSize: number }) {
    const data = await this.user.find({
      relations: ['articles'],
      where: {
        username: Like(`%${query.keyWord}%`)
      },
   
      skip: (query.page - 1) * query.pageSize,
      take: query.pageSize,
    })
    const total = await this.user.count({
      where: {
        username: Like(`%${query.keyWord}%`)
      },
    })
    return {
      data,
      total
    }
  }
  async findOne(findUserDto:findUserDto) {
    const data = await this.user.findOne({
      relations: ['articles'],
      where: {
        userid:findUserDto.userid
      }
    })
    return data
  }

  async update(updateUserDto: UpdateUserDto) {
    const { userid, ...rest } = updateUserDto;
    // 只允许更新用户表自身字段
    const updateData: Partial<User> = { ...rest };
    // 移除一对多关系字段
    delete (updateData as any).articles;
    delete (updateData as any).comments;
    return this.user.update(userid, updateData);
  }

  remove(id: number) {
    return this.user.delete(id)
  }
}